// controllers/userController.js
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { pool } = require('../config/db');
const { JWT_SECRET, JWT_EXPIRES_IN } = process.env;
const {upload} =require('../util/uploadConfig')
const { body, query, validationResult } = require('express-validator');
const path =require('path');
const { create } = require('domain');

const userDataValidator=[
  body('username')
    .notEmpty().withMessage('用户名不能为空')
    .isLength({min:4,max:16}).withMessage('用户名格式错误'),
  
  body('pass')
    .notEmpty().withMessage('密码不能为空')
    .isLength({min:6,max:50}).withMessage('密码格式错误'),
  
  body('email')
    .notEmpty().withMessage('邮箱不能为空')
    .isLength({max:100}).withMessage('邮箱格式不正确'),

    // 2. 必须添加验证结果处理中间件
    (req, res, next) => {
      console.log('FormData 解析后的数据：', req.body);
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        code: 400, 
        msg: '注册参数验证失败', // 总错误描述
        errors: errors.array().map(item => ({
          field: item.param, // 字段名（前端用这个匹配表单）
          message: item.msg // 具体错误信息
        })) 
      });
    }
    next();
  }
];

// 登录接口（修正 avatar 拼写）
exports.login = async (req, res, next) => {
  try {
    const { username, pass } = req.body;
    console.log('登录请求参数:', { username, pass });

    // 1. SQL 查询：avater → avatar（与表字段一致）
    const [users] = await pool.query(
      'SELECT id, username, pass, email, role, avatar, created FROM users WHERE username = ?',
      [username]
    );

    if (users.length === 0) {
      const error = new Error('用户名或密码错误');
      error.statusCode = 401;
      throw error;
    }
    const user = users[0];

    // 2. 密码验证（明文比对，适配测试数据）
    const isPasswordValid = (pass === user.pass);

    if (!isPasswordValid) {
      const error = new Error('用户名或密码错误');
      error.statusCode = 401;
      throw error;
    }

    // 3. 生成 JWT 令牌
    const token = jwt.sign(
      { id: user.id, username: user.username, role: user.role },
      JWT_SECRET,
      { expiresIn: JWT_EXPIRES_IN || '24h' }
    );

    // 4. 返回用户信息：avater → avatar
    const userData = {
      id: user.id,
      username: user.username,
      email: user.email,
      role: user.role,
      avatar: user.avatar || '', // 修正拼写
      created: user.created
    };

    res.status(200).json({
      code: 200,
      msg: user.username,
      data: { user: userData, token }
    });

  } catch (err) {
    console.error('登录接口错误:', err);
    next(err);
  }
};

// 注册接口（修正 avatar 拼写）
exports.register = [upload,...userDataValidator,async (req, res, next) => {
  try {

    const { username, pass, email } = req.body; // 接收 avatar 参数
    const avatarFile= req.file;
    let avatar='';
    if(avatarFile){
      const publicDir=path.join(__dirname,'../public');
      avatar=path.relative(publicDir,avatarFile.path);
      avatar=avatar.replace(/\\/g,'/');
    }
    
    // 插入新用户：avater → avatar（表字段名）
    const [result] = await pool.query(
      `INSERT INTO users (username, pass, email, role, avatar) 
       VALUES (?, ?, ?, 0, ?)`, // 修正字段名
      [username, pass, email, avatar || ''] // 传入 avatar（默认空）
    );

    res.status(200).json({
      code:200,
      msg: '注册成功',
      data: { userId: result.insertId, username }
    });

  } catch (err) {
    console.error('注册接口错误:', err);
    next(err);
  }
}];

// 获取当前用户信息（修正 avatar 拼写）
exports.getCurrentUser = async (req, res, next) => {
  try {
    // SQL 查询：avater → avatar
    const [users] = await pool.query(
      'SELECT id, username, email, role, avatar, created FROM users WHERE id = ?',
      [req.user.id]
    );

    if (users.length === 0) {
      const error = new Error('用户不存在');
      error.statusCode = 404;
      throw error;
    }

    // 返回用户信息：avater → avatar
    res.status(200).json({
      code:200,
      msg:'用户信息获取成功',
      data: {
        user: {
          id: users[0].id,
          username: users[0].username,
          email: users[0].email,
          role: users[0].role,
          avatar: users[0].avatar || '', // 修正拼写
          created: users[0].created
        }
      }
    });

  } catch (err) {
    console.error('获取用户信息错误:', err);
    next(err);
  }
};